package org.idea.qiyu.mq.local.queue.jdk;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @Author linhao
 * @Date created in 7:11 下午 2021/11/26
 */
public class ArrayBlockingQueueDemo {

    static ArrayBlockingQueue<String> arrayBlockingQueue = new ArrayBlockingQueue(19);

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        arrayBlockingQueue.offer("item1");
        arrayBlockingQueue.offer("item2");
        arrayBlockingQueue.offer("item3");
        Thread thread = new Thread(new ConsumerThread());
        thread.start();
        countDownLatch.await();
    }

    static class ConsumerThread implements Runnable {

        @Override
        public void run() {
            while (true) {
                try {
                    Thread.sleep(1000);
                    //弹出元素过程中，超时时长为3秒，如果超过3秒没有弹出元素
                    String item = arrayBlockingQueue.poll(3000, TimeUnit.MILLISECONDS);
                    System.out.println("弹出元素：" + item);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
